import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import os
import warnings
warnings.filterwarnings('ignore')
pd.set_option('max_colwidth',200)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.width', 1000)

root_path = os.path.abspath('../../')

font1 = {
    'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 16,
}

fontlegend = {
    'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 14,
}

data_path = root_path + "/asset/mergingData100m.csv"
ori_data = pd.read_csv(data_path)

mergingData = ori_data[
    (ori_data['MergingState']==True)
    & (ori_data['RouteClass']=='entry')
    & (ori_data['BreakRuleState']=='None')
    & (ori_data['MergingDistance'] !='None')
    & (ori_data['MaxLateralSpeed'] !='None')
    & (ori_data['MergingType'] != 'None')
    ]

mergingData['MergingDistance'] = mergingData['MergingDistance'].astype('float')
mergingData['MergingDuration'] = mergingData['MergingDuration'].astype('float')
mergingData['MaxLateralSpeed'] = mergingData['MaxLateralSpeed'].astype('float')
mergingData['MaxiLateralAcc'] = mergingData['MaxiLateralAcc'].astype('float')
mergingData['MergingDistanceRatio'] = mergingData['MergingDistanceRatio'].astype('float')
mergingData['totalvelocity'] = np.sqrt(np.square(mergingData['xVelocity'])+np.square(mergingData['yVelocity']))

statistc = pd.DataFrame()

for curLocation, curLocationGroup in mergingData.groupby("location"):
    for curMergingType, curMergingTypeGroup in curLocationGroup.groupby("MergingType"):
        curDic = {}
        curDic["location"] = curLocation
        curDic["MergingType"] = curMergingType

        if curMergingType =="G" or curMergingType =="H":
            continue

        curDic["trafficFlowArea4"] = np.mean(curMergingTypeGroup["trafficFlowArea4"])
        curDic["trafficFlowArea5"] = np.mean(curMergingTypeGroup["trafficFlowArea5"])
        curDic["trafficDensityArea4"] = np.mean(curMergingTypeGroup["trafficDensityArea4"])
        curDic["trafficDensityArea5"] = np.mean(curMergingTypeGroup["trafficDensityArea5"])
        curDic["trafficSpeedArea4"] = np.mean(curMergingTypeGroup["trafficSpeedArea4"])
        curDic["trafficSpeedArea5"] = np.mean(curMergingTypeGroup["trafficSpeedArea5"])
        statistc = pd.concat([statistc, pd.DataFrame([curDic])], axis=0)

FONTSIZE = 16
plt.figure(figsize=(15, 8))
plt.style.use('seaborn-colorblind')
mergingData['MergingDistanceRatio'] = mergingData['MergingDistanceRatio'].astype('float')
mergingData.sort_values(by="vehicleClass", inplace=True)

ax1 = plt.subplot(2,3,1)
g1 = sns.scatterplot(x="trafficDensityArea4", y="trafficFlowArea4", data=mergingData[mergingData["location"]==2], palette="Paired_r",alpha=0.8)
plt.xticks(fontsize=FONTSIZE)
plt.yticks(fontsize=FONTSIZE)
plt.yticks([0,500,1000,1500,2000,2500])
plt.ylabel("flow(veh/h)", font1)
plt.xlabel("density(veh/km)", font1)
sns.set_context("notebook")
plt.grid(ls='-', axis="both")
plt.title("Upstream", font1)

ax2 = plt.subplot(2,3,2)
g2 = sns.scatterplot(x="trafficFlowArea4", y="trafficSpeedArea4", data=mergingData[mergingData["location"]==2], palette="Paired_r",alpha=0.8)
plt.xticks(fontsize=FONTSIZE)
plt.yticks(fontsize=FONTSIZE)
plt.xticks([0,500,1000,1500,2000,2500])
plt.yticks([0,20,40,60,80,100,120,140,160,180,200])
plt.xlabel("flow(veh/h)", font1)
plt.ylabel("speed(km/m)", font1)
plt.grid(ls='-', axis="both")
plt.title("Upstream", font1)

ax3 = plt.subplot(2,3,3)
curstatisticlocation2 = statistc[statistc["location"]==2]
plt.xticks(fontsize=FONTSIZE)
plt.yticks(fontsize=FONTSIZE)
plt.plot(curstatisticlocation2["trafficFlowArea4"].values,'-',linewidth =2.5, label="2", alpha=0.9)
plt.xticks([0,1,2,3,4,5], ["A","B","C","D","E","F"])
plt.ylabel("flow(veh/h)", font1)
plt.xlabel("merging scenario", font1)
plt.grid(ls='-', axis="both")
plt.title("Upstream", font1)

ax4 = plt.subplot(2,3,4)
g4 = sns.scatterplot(x="trafficDensityArea5", y="trafficFlowArea5", data=mergingData[mergingData["location"]==2],  palette="Paired_r",alpha=0.8)
plt.xticks(fontsize=FONTSIZE)
plt.yticks(fontsize=FONTSIZE)
plt.yticks([0,500,1000,1500,2000,2500])
plt.ylabel("flow(veh/h)", font1)
plt.xlabel("density(veh/km)", font1)
plt.grid(ls='-', axis="both")
plt.title("Downstream", font1)

ax5 = plt.subplot(2,3,5)
g5 = sns.scatterplot(x="trafficFlowArea5", y="trafficSpeedArea5", data=mergingData[mergingData["location"]==2],  palette="Paired_r",alpha=0.8)
plt.xticks(fontsize=FONTSIZE)
plt.yticks(fontsize=FONTSIZE)
plt.xticks([0,500,1000,1500,2000,2500])
plt.yticks([0,20,40,60,80,100,120,140,160,180,200])
plt.xlabel("flow(veh/h)", font1)
plt.ylabel("speed(km/m)", font1)
plt.grid(ls='-', axis="both")
plt.title("Downstream", font1)

ax6 = plt.subplot(2,3,6)
plt.plot(curstatisticlocation2["trafficFlowArea5"].values,'-',linewidth =2.5, label="2", alpha=0.9)
plt.xticks(fontsize=FONTSIZE)
plt.yticks(fontsize=FONTSIZE)
plt.xlabel("merging scenario", font1)
plt.xticks([0,1,2,3,4,5], ["A","B","C","D","E","F"])
plt.ylabel("flow(veh/h)", font1)
plt.grid(ls='-', axis="both")
plt.title("Downstream", font1)

plt.tight_layout()
plt.show()
